from flask import Flask

from flask_sqlalchemy import SQLAlchemy
from app.libs.utils.mock import Mock
from app.models.config import Config
# import pymysql
# pymysql.install_as_MySQLdb()  # 规避数据库连接问题 # 使用mysql时需要


def create_app():
    # app = Flask(__name__, static_folder='', static_url_path='', static_host='')
    # @NOTE 静态文件可以分离 并且设置域名，路径 蓝图也是同样可以的
    app = Flask(__name__)
    from .config import secure, setting
    app.config.from_object(secure)
    app.config.from_object(setting)

    from .models import db
    db.init_app(app=app)
    db.app = app
    # 模拟生成数据（自动创建管理员用户）  并 重置所有数据
    # mock_data(db, reset=True)
    # 初始化vs库

    register_blueprint(app=app)
    return app


def register_blueprint(app: Flask):
    from .api import bp_api
    app.register_blueprint(bp_api)


def mock_data(db: SQLAlchemy, reset):

    # 添加超级管理员
    def add_config():
        config = Config(id=1, step='fps', speed=3.0)
        session.add(config)
    if reset:
        with Mock(db, reset=reset) as mock:
            session = mock.get_session()
            add_config()
    else:
        has_table = db.engine.dialect.has_table(
            db.engine.connect(), "config")
        if not has_table:
            with Mock(db, reset=True) as mock:
                session = mock.get_session()
                add_config()
